<template>
  <div class="content-wrapper">
    <!-- <div class="content-header">公司/部门</div> -->
    <div class="content-container">
      <el-container>
        <el-aside class="tree-tainer">
          <h6 class="info-color">企业组织架构</h6>
          <div class="filter-container">
            <div class="filter-item">
              <span v-if="selectedUserGroupNode" class="selected-tree-node">{{selectedUserGroupNode.label}}</span>
            </div>
            <div class="filter-item">
              <el-tooltip effect="dark" content="添加" placement="top">
                <el-button class="filter-item" size="mini" round circle icon="el-icon-plus" @click="handleCreate"></el-button>
              </el-tooltip>
              <el-tooltip effect="dark" content="编辑" placement="top">
                <el-button class="filter-item" size="mini" round circle icon="el-icon-edit" @click="handleUpdateNode"></el-button>
              </el-tooltip>
              <el-tooltip effect="dark" content="删除" placement="top">
                <el-button class="filter-item" size="mini" round circle icon="el-icon-delete danger-color" @click="handleDelete(selectedUserGroupNode.value)"></el-button>
              </el-tooltip>
              <el-tooltip effect="dark" content="管理员工" placement="top">
                <el-button class="filter-item" size="mini" round circle icon="el-icon-user" @click="handleMember"></el-button>
              </el-tooltip>
              <el-tooltip effect="dark" content="刷新" placement="top">
                <el-button class="filter-item" size="mini" round circle icon="el-icon-refresh-right" @click="getTree"></el-button>
              </el-tooltip>
            </div>
          </div>
          <div class="my-tree">
          <el-tree ref="userGroupTree"
            :data="userGroupTree"
            empty-text="未找到匹配的数据"
            :default-expand-all="true"
            :expand-on-click-node="false"
            :highlight-current="true"
            @node-click="handleUserGroupNodeClick"
          ></el-tree>
          </div>
        </el-aside>
        <el-main>
          <el-table
            v-loading="listLoading"
            :data="list"
            highlight-current-row
            :cell-class-name="changeCellStyle"
          >
            <el-table-column label="名称" prop="userGroupName" min-width="200px" />
            <el-table-column label="简称" prop="userGroupAbbr" width="100px" />
            <el-table-column label="上级" min-width="200px">
              <template slot-scope="{row}">
                <span v-if="row.parentUserGroup !== undefined && row.parentUserGroup !== null">{{ row.parentUserGroup.userGroupName }}</span>
              </template>
            </el-table-column>
            <!-- <el-table-column label="角色" width="120px">
              <template slot-scope="{row}">
                <span v-if="row.roleList !== null">{{ renderRole(row.roleList) }}</span>
              </template>
            </el-table-column> -->
            <el-table-column label="排序" prop="sequence" width="60px" />
            <el-table-column label="操作" align="center" width="120px" fixed="right">
              <template slot-scope="{row}">
                <el-button type="text" size="mini" @click="handleDelete(row.userGroupId)">
                  删除
                </el-button>
                <el-button type="text" size="mini" @click="handleUpdate(row)">
                  修改
                </el-button>
              </template>
            </el-table-column>
          </el-table>

          <pagination v-show="total>0" :total="total" :page-number.sync="listQuery.pageNumber" :page-size.sync="listQuery.pageSize" @pagination="getList" />

          <el-drawer :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
            <el-form ref="dataForm" :rules="rules" :model="temp" label-position="right" label-width="120px" style="width: 480px;">
              <el-form-item label="名称" prop="userGroupName">
                <el-input v-model.trim="temp.userGroupName" />
              </el-form-item>
<!--              <el-form-item label="简称" prop="userGroupAbbr">-->
<!--                <el-input v-model.trim="temp.userGroupAbbr" />-->
<!--              </el-form-item>-->
              <el-form-item label="排序" prop="sequence">
                <el-input v-model.trim="temp.sequence" type="number" />
              </el-form-item>
              <el-form-item label="上级">
                <el-cascader :key="isParentUserGroupCascaderShow" v-model="selectedParentUserGroupId" :options="parentUserGroupOptions" :props="{ checkStrictly: true }" filterable clearable @change="handleParentUserGroupIdChange" style="width: 100%;" />
              </el-form-item>
              <!-- <el-form-item label="角色（多选）">
                <el-select :key="isRoleIdShow" v-model="temp.roleIdList" multiple class="filter-item" placeholder="请选择">
                  <el-option v-for="item in roleOptions" :key="item.key" :label="item.value" :value="item.key" />
                </el-select>
              </el-form-item> -->

              <el-form-item>
                <el-button @click="dialogFormVisible = false">
                  取消
                </el-button>
                <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">
                  提交
                </el-button>
              </el-form-item>
            </el-form>
          </el-drawer>
          <Member :dialogVisible="dialogVisibleMemeber"></Member>
        </el-main>
      </el-container>
    </div>
  </div>
</template>

<script>
import { saveUserGroup, updateUserGroup, deleteUserGroup, getUserGroup, listUserGroup, listUserGroupTreeItemForManage, listRoleId } from '@/api/uc/userGroup'
// import { listRoleItem } from '@/api/uc/role'
import { findAndAccept3 } from '@/utils/tree'
import Pagination from '@/components/Pagination'
import waves from '@/directive/waves'
import Member from '@/views/management/userGroup/member.vue'

export default {
  components: { Pagination, Member },
  directives: { waves },
  data() {
    const TYPE = 0;
    return {
      constType: TYPE,
      userGroupTree: [],
      // filterText: '',
      selectedUserGroupNode: null,
      dialogVisibleMemeber: false,
      list: null,
      total: 0,
      listLoading: false,
      listQuery: {
        pageNumber: 1,
        pageIndex: 0,
        pageSize: 20,
        type: TYPE,
        parentUserGroupId: null,
        withParent: true,
        withRole: false
      },
      temp: {
        userGroupId: undefined,
        userGroupAbbr: '',
        userGroupName: '',
        sequence: 1,
        parentUserGroupId: null,
        type: TYPE,
        roleIdList: null
      },
      parentUserGroupOptions: null,
      selectedParentUserGroupId: [],
      isParentUserGroupCascaderShow: '0',
      // roleOptions: null,
      // isRoleIdShow: '0',
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: '修改',
        create: '新增'
      },
      rules: {
        userGroupAbbr: [
          { required: true, message: '编码不能为空', trigger: 'change' },
          { pattern: /^[a-zA-Z0-9_-]+$/, message: '编码由a-zA-Z0-9_-等字母组成', trigger: 'change' }
        ],
        userGroupName: [{ required: true, message: '名称不能为空', trigger: 'change' }],
        sequence: [{ required: true, message: '排序不能为空', trigger: 'change' }]
      }
    }
  },
  mounted() {
    this.getTree()
  },
  // watch: {
  //   filterText(val) {
  //     this.$refs.userGroupTree.filter(val);
  //   }
  // },
  methods: {
    changeCellStyle({ row, column, rowIndex, columnIndex }) {
      if (columnIndex === 5 && row.roleList === null) {
        return 'backWarning'
      }
    },
    // filterUserGroupNode(value, data) {
    //   if (!value) return true;
    //   return data.label.indexOf(value) !== -1;
    // },
    getTree() {
      listUserGroupTreeItemForManage({ type: this.constType, parentUserGroupId: null })
        .then(response => {
          this.userGroupTree = response.data
          this.list = null
          this.total = 0
        })
    },
    handleUserGroupNodeClick(data) {
      this.selectedUserGroupNode = data
      this.listQuery.parentUserGroupId = data.value
      this.getList()
    },
    getList() {
      this.listQuery.pageIndex = this.listQuery.pageNumber - 1
      this.listLoading = true
      listUserGroup(this.listQuery).then(response => {
        this.list = response.data.rows
        this.total = response.data.total
        this.listLoading = false
      })
    },
    handleFilter() {
      this.listQuery.pageNumber = 1
      this.getList()
    },
    // renderRole(roleList) {
    //   const a = []
    //   roleList.forEach(e => {
    //     a.push(e.name)
    //   })
    //   return a.toString()
    // },
    resetTemp() {
      this.temp = {
        userGroupId: undefined,
        userGroupName: '',
        sequence: 1,
        parentUserGroupId: null,
        type: this.constType,
        // roleIdList: null
      }
    },
    // showRoleOptions(onOptionsLoad) {
    //   if (this.roleOptions === null) {
    //     listRoleItem({ typeList: [1, 2] }).then(response => {
    //       this.roleOptions = response.data
    //       onOptionsLoad && onOptionsLoad()
    //     })
    //   } else {
    //     onOptionsLoad && onOptionsLoad()
    //   }
    // },
    // setRoleIdList() {
    //   ++this.isRoleIdShow
    //   listRoleId({ userGroupId: this.temp.userGroupId }).then(response => {
    //     this.temp.roleIdList = response.data
    //   })
    // },
    showParentUserGroupOptions(onOptionsLoad) {
      if (this.parentUserGroupOptions === null) {
        // listUserGroupTreeItemForManage({ type: this.constType, parentUserGroupId: null }).then(response => {
        //   this.parentUserGroupOptions = response.data
        //   onOptionsLoad && onOptionsLoad()
        // })
        this.parentUserGroupOptions = this.userGroupTree
        onOptionsLoad && onOptionsLoad()
      } else {
        onOptionsLoad && onOptionsLoad()
      }
    },
    setParentUserGroupId() {
      const parentStack = findAndAccept3(this.parentUserGroupOptions,
        e => this.temp.parentUserGroupId === e.value,
        e => { })
      const a = []
      parentStack.forEach(node => {
        a.push(node.value)
      })
      this.selectedParentUserGroupId = a
    },
    clearParentUserGroupCascader() {
      this.selectedParentUserGroupId.length = 0
      ++this.isParentUserGroupCascaderShow
    },
    handleParentUserGroupIdChange(value) {
      if (value) {
        this.temp.parentUserGroupId = value[value.length - 1]
      }
    },
    handleCreate() {
      this.resetTemp()
      this.clearParentUserGroupCascader()
      if(this.selectedUserGroupNode !== null) {
        this.temp.parentUserGroupId = this.selectedUserGroupNode.value
        this.showParentUserGroupOptions(this.setParentUserGroupId)
      } else {
        this.showParentUserGroupOptions()
      }
      // this.showRoleOptions()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          saveUserGroup(this.temp).then(() => {
            this.list.unshift(this.temp)
            this.dialogFormVisible = false
            this.$message.success("操作成功")
            this.handleFilter()
            this.getTree()
            this.getList()
          })
        }
      })
    },
    handleUpdateNode() {
      getUserGroup({userGroupId: this.selectedUserGroupNode.value}).then(res => {
        this.handleUpdate(res.data)
      })
    },
    handleUpdate(row) {
      this.temp = Object.assign({}, row)
      this.clearParentUserGroupCascader()
      // this.showRoleOptions(this.setRoleIdList)
      this.showParentUserGroupOptions(this.setParentUserGroupId)
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          const tempData = Object.assign({}, this.temp)
          updateUserGroup(tempData).then(() => {
            const index = this.list.findIndex(v => v.id === this.temp.id)
            this.list.splice(index, 1, this.temp)
            this.dialogFormVisible = false
            this.$message.success("操作成功")
            this.handleFilter()
            this.getTree()
          })
        }
      })
    },
    handleDelete(userGroupId) {
      if(!userGroupId) {
        this.$message({
          message: '请选择要删除的数据',
          type: 'warning'
        })
        return
      }
      this.$confirm('此操作将删除, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteUserGroup({
          userGroupId: userGroupId
        }).then(response => {
          this.getTree()
          this.$message.success("操作成功")
          this.getList()
        })
      })
    },
    handleMember() {
      if (!this.selectedUserGroupNode) {
        this.$message.info("请先选择部门后操作")
        return
      }
      this.dialogVisibleMemeber = {
        dialogVisible: true,
        userGroupId: this.selectedUserGroupNode.value
      }
    }

  }
}
</script>

<style scoped>

.tree-tainer {
  border-style:solid;
  border-width: 0 1px 0 0;
  border-color: #eee;
}

.selected-tree-node {
  font-size: 14px;
}
.my-tree{
  height: 80vh;
  overflow:auto
}

</style>
